package com.chu.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;
        String requestURI = request1.getRequestURI();

        if(requestURI.endsWith("login.jsp")||requestURI.endsWith("login")||requestURI.endsWith(".css")||requestURI.contains("/img")||requestURI.equals("/")){
            chain.doFilter(request, response);
        }else{
            String username = (String) request1.getSession().getAttribute("username");
            if(username==null){
                response1.setContentType("text/html;charset=UTF-8");
                response1.getWriter().write("<script>alert('请先登录！');redirect:login.jsp</script>");
            }else{
                chain.doFilter(request, response);
            }
        }

    }

    @Override
    public void destroy() {

    }
}
